// pages/text_view/text_view.ts

/**
 * 考试结果数据接口
 */
interface ExamResult {
  score: number;
  totalQuestions: number;
  correctCount: number;
  wrongCount: number;
  accuracy: string;
  answerHistory: Array<{
    questionId: number;
    userAnswer: string;
    correctAnswer: string;
    isCorrect: boolean;
  }>;
  questions: Question[];
  
  // 时间数据
  examStartTime: number;
  examEndTime: number;
  totalTimeSpent: number; // 总耗时（秒）
  questionTimeRecords: Array<{
    questionId: number;
    timeSpent: number; // 该题耗时（秒）
  }>;
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    score: 0, // 最终得分
    totalQuestions: 0, // 总题目数
    correctCount: 0, // 答对题数
    wrongCount: 0, // 答错题数
    accuracy: '0', // 正确率
    answerHistory: [] as Array<{
      questionId: number;
      userAnswer: string;
      correctAnswer: string;
      isCorrect: boolean;
      questionText: string;
      userAnswerText: string;
      correctAnswerText: string;
    }>, // 详细答题历史
    showDetail: false, // 是否显示详细答题记录
    
    // 数据可视化相关
    ringProgress: 0, // 环形图进度
    correctPercent: 0, // 答对百分比
    wrongPercent: 0, // 答错百分比
    gradeLevel: '', // 成绩等级
    gradeIcon: '', // 等级图标
    gradeTitle: '', // 等级标题
    gradeDescription: '', // 等级描述
    timeSpent: '', // 答题用时
    averageTime: '', // 平均每题用时
    
    // 时间统计详情
    examStartTime: '', // 考试开始时间（格式化）
    examEndTime: '', // 考试结束时间（格式化）
    fastestTime: '', // 最快题目用时
    slowestTime: '', // 最慢题目用时
    fastestQuestionId: 0, // 最快题目ID
    slowestQuestionId: 0, // 最慢题目ID
    
    // 错题分析弹窗
    showWrongModal: false, // 是否显示错题分析弹窗
    wrongAnswers: [] as Array<{
      questionId: number;
      questionIndex: number;
      questionText: string;
      userAnswer: string;
      userAnswerText: string;
      correctAnswer: string;
      correctAnswerText: string;
    }>, // 错题列表
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    console.log('text_view页面开始加载');
    this.loadExamResult();
  },

  /**
   * 加载考试结果数据，包含重试机制
   * @param retryCount 重试次数，默认为0
   */
  loadExamResult(retryCount: number = 0) {
    // console.log(`尝试加载考试结果数据，重试次数: ${retryCount}`);
    
    // 获取考试结果数据
    const app = getApp<IAppOption>();
    const examResult = (app as any).examResult as ExamResult;
    
    // console.log('从全局获取的考试结果:', examResult ? '数据存在' : '数据不存在');

    if (examResult) {
      // console.log('考试结果数据加载成功，开始处理数据');
      
      // 处理答题历史，补充题目文本和选项文本
      const detailedHistory = examResult.answerHistory.map(item => {
        const question = examResult.questions.find(q => q.id === item.questionId);
        return {
          ...item,
          questionText: question?.question || '未知题目',
          userAnswerText: String(question?.options[item.userAnswer as keyof typeof question.options] || item.userAnswer),
          correctAnswerText: String(question?.options[item.correctAnswer as keyof typeof question.options] || item.correctAnswer)
        };
      });

      // 计算数据可视化相关数据
      const accuracyNum = parseFloat(examResult.accuracy);
      const ringProgress = (accuracyNum / 100) * 360; // 环形图角度为360度
      const correctPercent = examResult.totalQuestions > 0 ? (examResult.correctCount / examResult.totalQuestions) * 100 : 0;
      const wrongPercent = examResult.totalQuestions > 0 ? (examResult.wrongCount / examResult.totalQuestions) * 100 : 0;
      
      // 计算成绩等级
      const gradeData = this.calculateGrade(accuracyNum);
      
      // 计算答题用时（使用真实数据）
      const timeData = this.calculateTime(examResult);
      
      // 准备错题数据
      const wrongAnswers = detailedHistory
        .filter(item => !item.isCorrect)
        .map((item, index) => {
          const originalIndex = examResult.answerHistory.findIndex(h => h.questionId === item.questionId);
          return {
            questionId: item.questionId,
            questionIndex: originalIndex + 1,
            questionText: item.questionText,
            userAnswer: item.userAnswer,
            userAnswerText: String(item.userAnswerText),
            correctAnswer: item.correctAnswer,
            correctAnswerText: String(item.correctAnswerText)
          };
        });

      this.setData({
        score: examResult.score,
        totalQuestions: examResult.totalQuestions,
        correctCount: examResult.correctCount,
        wrongCount: examResult.wrongCount,
        accuracy: examResult.accuracy,
        answerHistory: detailedHistory,
        
        // 数据可视化数据
        ringProgress: ringProgress,
        correctPercent: correctPercent,
        wrongPercent: wrongPercent,
        gradeLevel: gradeData.level,
        gradeIcon: gradeData.icon,
        gradeTitle: gradeData.title,
        gradeDescription: gradeData.description,
        timeSpent: timeData.timeSpent,
        averageTime: timeData.averageTime,
        
        // 时间统计详情
        examStartTime: this.formatTime(examResult.examStartTime),
        examEndTime: this.formatTime(examResult.examEndTime),
        fastestTime: timeData.timeDistribution.fastest,
        slowestTime: timeData.timeDistribution.slowest,
        fastestQuestionId: timeData.timeDistribution.fastestQuestionId,
        slowestQuestionId: timeData.timeDistribution.slowestQuestionId,
        
        // 错题数据
        wrongAnswers: wrongAnswers
      });
      
      console.log('考试结果数据设置完成');
    } else {
      // 如果没有考试结果数据，尝试重试（最多3次）
      if (retryCount < 3) {
        console.log(`没有找到考试结果数据，${200}ms后进行第${retryCount + 1}次重试`);
        setTimeout(() => {
          this.loadExamResult(retryCount + 1);
        }, 200);
      } else {
        console.error('重试3次后仍然没有找到考试结果数据');
      wx.showModal({
          title: '数据加载失败',
          content: '没有找到考试结果数据，可能是数据传递出现问题。请重新完成考试。',
          showCancel: true,
          cancelText: '返回',
          confirmText: '重新考试',
          success: (res) => {
            if (res.confirm) {
              // 返回考试页面
              wx.reLaunch({
                url: '/pages/text/text'
              });
            } else {
              // 返回上一页
          wx.navigateBack();
            }
        }
      });
      }
    }
  },

  /**
   * 计算成绩等级
   * @param accuracy 正确率
   * @returns 等级信息
   */
  calculateGrade(accuracy: number) {
    if (accuracy >= 90) {
      return {
        level: 'excellent',
        icon: '🏆',
        title: '优秀',
        description: '表现出色，继续保持！'
      };
    } else if (accuracy >= 80) {
      return {
        level: 'good',
        icon: '🎖️',
        title: '良好',
        description: '不错的成绩，再接再厉！'
      };
    } else if (accuracy >= 70) {
      return {
        level: 'fair',
        icon: '📈',
        title: '中等',
        description: '还有提升空间，加油！'
      };
    } else if (accuracy >= 60) {
      return {
        level: 'pass',
        icon: '📝',
        title: '及格',
        description: '刚好及格，需要更多练习'
      };
    } else {
      return {
        level: 'fail',
        icon: '📚',
        title: '不及格',
        description: '需要加强学习，再次挑战！'
      };
    }
  },

  /**
   * 计算答题时间（使用真实数据）
   * @param examResult 考试结果数据
   * @returns 时间信息
   */
  calculateTime(examResult: ExamResult) {
    const totalSeconds = examResult.totalTimeSpent;
    const questionTimeRecords = examResult.questionTimeRecords;
    
    // 格式化总耗时
    const totalMinutes = Math.floor(totalSeconds / 60);
    const remainingSeconds = totalSeconds % 60;
    const timeSpent = totalMinutes > 0 
      ? `${totalMinutes}分${remainingSeconds}秒` 
      : `${remainingSeconds}秒`;
    
    // 计算平均每题用时
    const averageSeconds = questionTimeRecords.length > 0 
      ? Math.round(totalSeconds / questionTimeRecords.length)
      : 0;
    const avgMinutes = Math.floor(averageSeconds / 60);
    const avgRemainingSec = averageSeconds % 60;
    const averageTime = avgMinutes > 0 
      ? `${avgMinutes}分${avgRemainingSec}秒` 
      : `${avgRemainingSec}秒`;
    
    // 统计时间分布
    const timeDistribution = this.analyzeTimeDistribution(questionTimeRecords);
    
    console.log('时间统计:', {
      总耗时: timeSpent,
      平均每题: averageTime,
      最快: timeDistribution.fastest,
      最慢: timeDistribution.slowest,
      题目时间记录: questionTimeRecords
    });
    
    return {
      timeSpent,
      averageTime,
      timeDistribution
    };
  },

  /**
   * 分析答题时间分布
   * @param questionTimeRecords 题目时间记录
   * @returns 时间分布统计
   */
  analyzeTimeDistribution(questionTimeRecords: Array<{questionId: number, timeSpent: number}>) {
    if (questionTimeRecords.length === 0) {
      return {
        fastest: '0秒',
        slowest: '0秒',
        fastestQuestionId: 0,
        slowestQuestionId: 0
      };
    }
    
    // 找出最快和最慢的题目
    let fastest = questionTimeRecords[0];
    let slowest = questionTimeRecords[0];
    
    questionTimeRecords.forEach(record => {
      if (record.timeSpent < fastest.timeSpent) {
        fastest = record;
      }
      if (record.timeSpent > slowest.timeSpent) {
        slowest = record;
      }
    });
    
    const formatTime = (seconds: number) => {
      const minutes = Math.floor(seconds / 60);
      const remainingSec = seconds % 60;
      return minutes > 0 ? `${minutes}分${remainingSec}秒` : `${remainingSec}秒`;
    };
    
    return {
      fastest: formatTime(fastest.timeSpent),
      slowest: formatTime(slowest.timeSpent),
      fastestQuestionId: fastest.questionId,
      slowestQuestionId: slowest.questionId
    };
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  /**
   * 切换显示/隐藏详细答题记录
   */
  toggleDetail() {
    this.setData({
      showDetail: !this.data.showDetail
    });
  },

  /**
   * 重新开始考试
   */
  restartExam() {
    wx.showModal({
      title: '确认重新开始',
      content: '确定要重新开始考试吗？当前成绩将被清除。',
      success: (res) => {
        if (res.confirm) {
          // 返回到考试页面
          wx.navigateBack();
        }
      }
    });
  },

  /**
   * 返回首页
   */
  goHome() {
    wx.reLaunch({
      url: '/pages/index/index'
    });
  },

  /**
   * 分享考试成绩
   */
  shareResult() {
    const { score, totalQuestions, correctCount, accuracy } = this.data;
    wx.showModal({
      title: '考试成绩',
      content: `我在在线考试中获得了 ${score} 分！\n总题数：${totalQuestions} 题\n答对：${correctCount} 题\n正确率：${accuracy}%`,
      showCancel: true,
      cancelText: '取消',
      confirmText: '好的',
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '可以通过右上角分享',
            icon: 'none',
            duration: 2000
          });
        }
      }
    });
  },

  /**
   * 打开AI对话页面
   */
  openAIChat() {
    console.log('点击AI对话按钮');
    console.log('当前页面路径:', getCurrentPages());
    
    if (this.data.wrongAnswers.length === 0) {
      wx.showToast({
        title: '恭喜！没有错题',
        icon: 'success',
        duration: 2000
      });
      return;
    }
    
    console.log('准备跳转到AI对话页面');
    console.log('错题数量:', this.data.wrongAnswers.length);
    
    // 准备传递给AI的错题数据
    const wrongQuestionsData = {
      wrongAnswers: this.data.wrongAnswers,
      examScore: this.data.score,
      accuracy: this.data.accuracy,
      totalQuestions: this.data.totalQuestions,
      correctCount: this.data.correctCount
    };
    
    // 跳转到AI对话页面
    wx.navigateTo({
      url: `/pages/chat_AI/chat_AI?examData=${encodeURIComponent(JSON.stringify(wrongQuestionsData))}`,
      success: (res) => {
        console.log('跳转AI对话页面成功:', res);
      },
      fail: (error) => {
        console.error('跳转AI对话页面失败:', error);
        console.error('错误详情:', JSON.stringify(error));
        
        // 尝试使用reLaunch
        console.log('尝试使用reLaunch跳转');
        wx.reLaunch({
          url: '/pages/chat_AI/chat_AI',
          success: (res) => {
            console.log('reLaunch成功:', res);
          },
          fail: (err) => {
            console.error('reLaunch也失败了:', err);
            wx.showModal({
              title: '跳转失败',
              content: `页面跳转失败，请检查页面是否存在。\n\n错误信息: ${error.errMsg || '未知错误'}`,
              showCancel: false,
              confirmText: '确定'
            });
          }
        });
      }
    });
  },

  /**
   * 查看错题详情 - 显示弹窗 (保留原功能作为备用)
   */
  viewWrongAnswers() {
    if (this.data.wrongAnswers.length === 0) {
      wx.showToast({
        title: '恭喜！没有错题',
        icon: 'success',
        duration: 2000
      });
      return;
    }
    
    this.setData({
      showWrongModal: true
    });
  },

  /**
   * 关闭错题分析弹窗
   */
  closeWrongModal() {
    this.setData({
      showWrongModal: false
    });
  },

  /**
   * 获取AI解释（错题弹窗中）
   * @param {any} event 事件对象
   */
  getAIExplanation(event: any) {
    const question = event.currentTarget.dataset.question;
    if (!question) return;

    // 跳转到AI解释页面
    this.navigateToAIPage(question);
  },

  /**
   * 获取AI解释（详细答题记录中）
   * @param {any} event 事件对象
   */
  getAIExplanationDetail(event: any) {
    const question = event.currentTarget.dataset.question;
    if (!question || question.isCorrect) return;

    // 跳转到AI解释页面
    this.navigateToAIPage(question);
  },

  /**
   * 跳转到AI解释页面
   * @param {any} question 题目数据
   */
  navigateToAIPage(question: any) {
    try {
      // 将题目数据编码后传递
      const questionData = encodeURIComponent(JSON.stringify(question));
      
      wx.navigateTo({
        url: `/pages/text_AI/text_AI?questionData=${questionData}`,
        fail: (error) => {
          console.error('跳转AI解释页面失败:', error);
          wx.showToast({
            title: '跳转失败，请重试',
            icon: 'none'
          });
        }
      });
    } catch (error) {
      console.error('编码题目数据失败:', error);
      wx.showToast({
        title: '数据处理失败',
        icon: 'none'
      });
    }
  },

  /**
   * 格式化时间
   * @param timestamp 时间戳
   * @returns 格式化后的时间字符串
   */
  formatTime(timestamp: number) {
    const date = new Date(timestamp);
    return date.toLocaleString();
  }
});